﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using ARR.UI.Models;
using ARR.UI.Commands;
using ARR.Entities;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;
using ARR.Shared;
using System.ServiceModel;
using ARR.UI.EnvoyImporterService;
using System.Windows.Threading;
using ARR.UI.ArticlesService;
using ARR.UI.Views;
using Telerik.Windows.Controls.GridView;
using Telerik.Windows.Controls;
using System.Windows.Controls;
using ARR.UI.ExcelImporterService;

namespace ARR.UI.ViewModels
{
    public class SalesImporterViewModel : WorkspaceViewModel
    {
        public ISalesImporterModel model;
        private ICommand cancelCommand;
        private ICommand nextCommand;
        private ICommand retryCommand;
        private ICommand saveCommand;
        private ICommand startCommand;
        private ICommand theoreticalMarginsCommand;



        public SalesImporterViewModel(ISalesImporterModel model)
        {
            base.DisplayName = Labels.ImportadorDeVentas;
            this.model = model;

            //TODO: chequear si existen registros en la tabla TempArticleSales
            if (WorkspaceData.Instance.Country.IsArticleMasterSeparateFile)
            {
                CurrentStep = 0;
                HasPassedCurrentStep = null;
            }
            else
            {
                CurrentStep = 1;
                HasPassedCurrentStep = true;
                Step1ImagePath = "/Images/Pass-16.png";
                OnPropertyChanged<SalesImporterViewModel>(p => p.HasPassedCurrentStep);
                CurrentStep = 2;
                HasPassedCurrentStep = true;
                Step2ImagePath = "/Images/Pass-16.png";
                OnPropertyChanged<SalesImporterViewModel>(p => p.HasPassedCurrentStep);
            }
        }




        public ICommand NextCommand
        {
            get
            {
                if (nextCommand == null)
                {
                    nextCommand = new RelayCommand(param => NextStep(), p => (HasPassedCurrentStep.HasValue && HasPassedCurrentStep.Value && CurrentStep != 4));
                }
                return nextCommand;
            }
        }

        public ICommand RetryCommand
        {
            get
            {
                if (retryCommand == null)
                {
                    retryCommand = new RelayCommand(param => RetryCurrentStep(), p => (HasPassedCurrentStep.HasValue && !HasPassedCurrentStep.Value));
                }
                return retryCommand;
            }
        }

        public ICommand StartCommand
        {
            get
            {
                if (startCommand == null)
                {
                    startCommand = new RelayCommand(param => NextStep(), p => CurrentStep == 0);

                }
                return startCommand;
            }
        }

        public ICommand SaveCommand
        {
            get
            {
                if (saveCommand == null)
                {
                    //TODO:
                }
                return saveCommand;
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new RelayCommand(param => Cancel());
                }
                return cancelCommand;
            }
        }

        public ICommand TheoreticalMarginsCommand
        {
            get
            {
                if (theoreticalMarginsCommand == null)
                {
                    theoreticalMarginsCommand = new RelayCommand(param => OpenTheoreticalMarginsPopup());
                }
                return theoreticalMarginsCommand;
            }
        }

        public ObservableCollection<ImporterResult> Results
        {
            get
            {
                return new ObservableCollection<ImporterResult>(model.Results.OrderBy(x => x.Description));
            }
        }

        public ObservableCollection<TempArticleSale> TempArticleSales
        {
            get
            {
                return model.TempArticleSales;
            }
        }

        public Visibility IsVisibleResultsGV
        {
            get
            {
                if (Results != null && Results.Any())
                {
                    return Visibility.Visible;
                }

                return Visibility.Collapsed;
            }
        }

        public Visibility IsVisibleTempArticleSalesGV
        {
            get
            {
                if (TempArticleSales != null && TempArticleSales.Any())
                {
                    return Visibility.Visible;
                }

                return Visibility.Collapsed;
            }
        }

        public string Step1ImagePath { get; set; }

        public string Step2ImagePath { get; set; }

        public string Step3ImagePath { get; set; }

        public string Step4ImagePath { get; set; }

        public int CurrentStep { get; set; }

        public bool? HasPassedCurrentStep { get; set; }

        public bool IsBusy { get; set; }



        public void TriggerPropertyChanged()
        {
            OnPropertyChanged<SalesImporterViewModel>(p => p.TempArticleSales);
        }


        private void Cancel()
        {

        }

        private void NextStep()
        {
            switch (CurrentStep)
            {
                case 0:
                    RunStep1();
                    break;
                case 1:
                    RunStep2();
                    break;
                case 2:
                    RunStep3();
                    break;
                case 3:
                    RunStep4();
                    break;
            }


            OnPropertyChanged<SalesImporterViewModel>(p => p.Results);
            OnPropertyChanged<SalesImporterViewModel>(p => p.IsVisibleResultsGV);

            if (CurrentStep < 4)
                CurrentStep += 1;
        }

        private void RetryCurrentStep()
        {
            CurrentStep -= 1;
            NextStep();
        }


        private void RunStep1()
        {
            switch (WorkspaceData.Instance.Country.SalesImporter)
            {
                case Constants.ImportSettings.StandardExcelImporter:
                    {
                        IsBusy = true;

                        ExcelImporterServiceClient excelService = new ExcelImporterServiceClient();

                        try
                        {
                            excelService.ImportArticleSalesStep1Completed += new EventHandler<ExcelImporterService.ImportArticleSalesStep1CompletedEventArgs>(excelService_ImportArticleSalesStep1Completed);
                            excelService.ImportArticleSalesStep1Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            excelService.Abort();
                            throw ex;
                        }

                        break;
                    }
                case Constants.ImportSettings.EnvoyImporter:
                    {
                        IsBusy = true;

                        EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

                        try
                        {
                            envoyService.ImportArticleSalesStep1Completed += new EventHandler<EnvoyImporterService.ImportArticleSalesStep1CompletedEventArgs>(envoyService_ImportArticleSalesStep1Completed);
                            envoyService.ImportArticleSalesStep1Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            envoyService.Abort();
                            throw ex;
                        }

                        break;
                    }
            }

            OnPropertyChanged<SalesImporterViewModel>(p => p.IsBusy);
        }

        private void RunStep2()
        {
            switch (WorkspaceData.Instance.Country.SalesImporter)
            {
                case Constants.ImportSettings.StandardExcelImporter:
                    {
                        IsBusy = true;

                        ExcelImporterServiceClient excelService = new ExcelImporterServiceClient();

                        try
                        {
                            excelService.ImportArticleSalesStep2Completed += new EventHandler<ExcelImporterService.ImportArticleSalesStep2CompletedEventArgs>(excelService_ImportArticleSalesStep2Completed);
                            excelService.ImportArticleSalesStep2Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            excelService.Abort();
                            throw ex;
                        }

                        break;
                    }
                case Constants.ImportSettings.EnvoyImporter:
                    {
                        IsBusy = true;

                        EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

                        try
                        {
                            envoyService.ImportArticleSalesStep2Completed += new EventHandler<EnvoyImporterService.ImportArticleSalesStep2CompletedEventArgs>(envoyService_ImportArticleSalesStep2Completed);
                            envoyService.ImportArticleSalesStep2Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            envoyService.Abort();
                            throw ex;
                        }

                        break;
                    }
            }

            OnPropertyChanged<SalesImporterViewModel>(p => p.IsBusy);
        }

        private void RunStep3()
        {
            EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

            try
            {
                envoyService.ImportArticleSalesStep3Completed += new EventHandler<ImportArticleSalesStep3CompletedEventArgs>(envoyService_ImportArticleSalesStep3Completed);
                envoyService.ImportArticleSalesStep3Async(WorkspaceData.Instance.RangeReview);
            }
            catch (Exception ex)
            {
                envoyService.Abort();
                throw ex;
            }

            IsBusy = true;
            OnPropertyChanged<SalesImporterViewModel>(p => p.IsBusy);
        }

        private void RunStep4()
        {
            EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

            try
            {
                envoyService.ImportArticleSalesStep4Completed += new EventHandler<ImportArticleSalesStep4CompletedEventArgs>(envoyService_ImportArticleSalesStep4Completed);
                envoyService.ImportArticleSalesStep4Async(WorkspaceData.Instance.RangeReview);
            }
            catch (Exception ex)
            {
                envoyService.Abort();
                throw ex;
            }

            IsBusy = true;
            OnPropertyChanged<SalesImporterViewModel>(p => p.IsBusy);
        }



        void excelService_ImportArticleSalesStep1Completed(object sender, ExcelImporterService.ImportArticleSalesStep1CompletedEventArgs e)
        {
            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                RunStep1Callback(e.Result);

            }
            else
            {
                (sender as ICommunicationObject).Abort();
                IsBusy = false;
                OnPropertyChanged<SalesImporterViewModel>(p => p.IsBusy);
                throw e.Error;
            }
        }

        void excelService_ImportArticleSalesStep2Completed(object sender, ExcelImporterService.ImportArticleSalesStep2CompletedEventArgs e)
        {
            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                RunStep2Callback(e.Result);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                IsBusy = false;
                OnPropertyChanged<SalesImporterViewModel>(p => p.IsBusy);
                throw e.Error;
            }
        }


        void envoyService_ImportArticleSalesStep1Completed(object sender, EnvoyImporterService.ImportArticleSalesStep1CompletedEventArgs e)
        {
            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                RunStep1Callback(e.Result);

            }
            else
            {
                (sender as ICommunicationObject).Abort();
                IsBusy = false;
                OnPropertyChanged<SalesImporterViewModel>(p => p.IsBusy);
                throw e.Error;
            }
        }

        void envoyService_ImportArticleSalesStep2Completed(object sender, EnvoyImporterService.ImportArticleSalesStep2CompletedEventArgs e)
        {
            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                RunStep2Callback(e.Result);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                IsBusy = false;
                OnPropertyChanged<SalesImporterViewModel>(p => p.IsBusy);
                throw e.Error;
            }
        }

        void envoyService_ImportArticleSalesStep3Completed(object sender, EnvoyImporterService.ImportArticleSalesStep3CompletedEventArgs e)
        {
            IsBusy = false;
            OnPropertyChanged<SalesImporterViewModel>(p => p.IsBusy);

            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                model.Results = e.Result;

                Step3ImagePath = "/Images/Pass-16.png";
                HasPassedCurrentStep = true;

                if (model.Results.Any())
                {
                    if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                    {
                        Step3ImagePath = "/Images/NotPass-16.png";
                        HasPassedCurrentStep = false;
                    }

                    if (model.Results.Any(r => r.ItemId != 0))
                    {
                        ArticlesServiceClient service = new ArticlesServiceClient();
                        try
                        {
                            var ids = model.Results.Select(r => r.ItemId).Where(r => r != 0).ToList();

                            List<TempArticleSale> sales = service.GetTempArticleSalesByIds(ids);
                            sales.AddRange(service.GetTempArticleSalesDuplicates());

                            List<TempArticleSale> nonDuplicateSales = new List<TempArticleSale>();
                            var idList = sales.Select(x => x.Id).Distinct().ToList();
                            foreach (int id in idList)
                            {
                                nonDuplicateSales.Add(sales.First(x => x.Id == id));
                            }

                            model.TempArticleSalesCache = new ObservableCollection<TempArticleSale>(nonDuplicateSales);

                            model.TempArticleSales = model.TempArticleSalesCache;

                            service.Close();
                        }
                        catch
                        {
                            service.Abort();
                            throw;
                        }
                    }
                }
                else
                {
                    model.TempArticleSales.Clear();
                }

                OnPropertyChanged<SalesImporterViewModel>(p => p.HasPassedCurrentStep);
                OnPropertyChanged<SalesImporterViewModel>(p => p.Step3ImagePath);
                OnPropertyChanged<SalesImporterViewModel>(p => p.TempArticleSales);
                OnPropertyChanged<SalesImporterViewModel>(p => p.Results);
                OnPropertyChanged<SalesImporterViewModel>(p => p.IsVisibleTempArticleSalesGV);
                OnPropertyChanged<SalesImporterViewModel>(p => p.IsVisibleResultsGV);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }

            
        }

        void envoyService_ImportArticleSalesStep4Completed(object sender, EnvoyImporterService.ImportArticleSalesStep4CompletedEventArgs e)
        {
            IsBusy = false;
            OnPropertyChanged<SalesImporterViewModel>(p => p.IsBusy);

            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                model.Results = e.Result;

                Step4ImagePath = "/Images/Pass-16.png";
                HasPassedCurrentStep = true;

                if (model.Results.Any())
                {
                    if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                    {
                        Step4ImagePath = "/Images/NotPass-16.png";
                        HasPassedCurrentStep = false;
                    }
                }

                OnPropertyChanged<SalesImporterViewModel>(p => p.HasPassedCurrentStep);
                OnPropertyChanged<SalesImporterViewModel>(p => p.Step4ImagePath);
                OnPropertyChanged<SalesImporterViewModel>(p => p.Results);
                OnPropertyChanged<SalesImporterViewModel>(p => p.IsVisibleResultsGV);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }

            
        }




        private void RunStep1Callback(List<ImporterResult> results)
        {
            model.Results = results;

            Step1ImagePath = "/Images/Pass-16.png";
            HasPassedCurrentStep = true;

            if (model.Results.Any())
            {
                if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                {
                    Step1ImagePath = "/Images/NotPass-16.png";
                    HasPassedCurrentStep = false;
                }
            }

            IsBusy = false;
            OnPropertyChanged<SalesImporterViewModel>(p => p.IsBusy);
            OnPropertyChanged<SalesImporterViewModel>(p => p.HasPassedCurrentStep);
            OnPropertyChanged<SalesImporterViewModel>(p => p.Step1ImagePath);
            OnPropertyChanged<SalesImporterViewModel>(p => p.Results);
            OnPropertyChanged<SalesImporterViewModel>(p => p.IsVisibleResultsGV);
        }

        private void RunStep2Callback(List<ImporterResult> results)
        {
            model.Results = results;

            Step2ImagePath = "/Images/Pass-16.png";
            HasPassedCurrentStep = true;

            if (model.Results.Any())
            {
                if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                {
                    Step2ImagePath = "/Images/NotPass-16.png";
                    HasPassedCurrentStep = false;
                }
            }

            IsBusy = false;
            OnPropertyChanged<SalesImporterViewModel>(p => p.IsBusy);
            OnPropertyChanged<SalesImporterViewModel>(p => p.HasPassedCurrentStep);
            OnPropertyChanged<SalesImporterViewModel>(p => p.Step2ImagePath);
            OnPropertyChanged<SalesImporterViewModel>(p => p.Results);
            OnPropertyChanged<SalesImporterViewModel>(p => p.IsVisibleResultsGV);
        }


        private void OpenTheoreticalMarginsPopup()
        {
            var selecteds = this.model.Results.Where(x => x.IsSelected).Select(x => x.ItemId).Distinct();

            if (!selecteds.Any())
            {
                (new Alert(Messages.MargenTeoricoCategoriasSeleccionados, Labels.Advertencia, AlertType.Warning)).ShowDialog();
            }
            else
            {
                TheoreticalMarginsViewModel vm = new TheoreticalMarginsViewModel(selecteds, true);
                TheoreticalMarginsPopupView popup = new TheoreticalMarginsPopupView();
                popup.DataContext = vm;


                bool? result = popup.ShowDialog();

                if (result.HasValue && result.Value)
                {
                    RetryCurrentStep();
                }
            }
        }
    }


}
